package cn.ilikes.tools.hbase.jpa.clazzes.resources;

import java.io.ByteArrayOutputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;

import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;

public class ClasspathResources extends Resources {

	private static Logger logger = Loggerfactory.instance(ClasspathResources.class);

	private void loadResourceContent(String resource, String pack) {
		File resourceFile = new File(resource);
		String entryName = "";

		if (pack.length() > 0) {
			entryName = pack + "/";
		}
		entryName += resourceFile.getName();
		saveEntry(entryName);

	}

	/**
	 * Attempts to load a remote resource (jars, properties files, etc)
	 * 
	 * @param url
	 */
	private void loadRemoteResource(URL url) {
		if (url.toString().toLowerCase().endsWith(".jar")) {
			loadJar(url);
			return;
		}
	}

	/**
	 * Reads the class content
	 * 
	 * @param clazz
	 * @param pack
	 */
	private void loadClassContent(String clazz, String pack) {
		File cf = new File(clazz);

		String entryName = pack + "/" + cf.getName();

		saveEntry(entryName);

	}

	/**
	 * Reads local and remote resources
	 * 
	 * @param url
	 */
	public void loadResource(URL url) {
		Loggerfactory.info(logger, "loadResource    :  " + url.toString());
		try {
			// Is Local
			loadResource(new File(url.toURI()), "");
		} catch (IllegalArgumentException iae) {
			// Is Remote
			loadRemoteResource(url);
		} catch (URISyntaxException e) {
			throw new ClasspathResourcesException("URISyntaxException", e);
		}
	}

	/**
	 * Reads local resources from - Jar files - Class folders - Jar
	 * Library folders
	 * 
	 * @param path
	 */
	public void loadResource(String path) {

		File fp = new File(path);

		if (!fp.exists()) {
			throw new ClasspathResourcesException("File/Path does not exist");
		}

		loadResource(fp, "");
	}

	/**
	 * Reads local resources from - Jar files - Class folders - Jar
	 * Library folders
	 * 
	 * @param fol
	 * @param packName
	 */
	private void loadResource(File fol, String packName) {
		if (fol.isFile()) {
			if (fol.getName().toLowerCase().endsWith(".class")) {
				loadClassContent(fol.getAbsolutePath(), packName);
			} else {
				if (fol.getName().toLowerCase().endsWith(".jar")) {
					loadJar(fol.getAbsolutePath());
				} else {
					loadResourceContent(fol.getAbsolutePath(), packName);
				}
			}

			return;
		}

		if (fol.list() != null) {
			for (String f : fol.list()) {
				File fl = new File(fol.getAbsolutePath() + "/" + f);

				String pn = packName;

				if (fl.isDirectory()) {

					if (!pn.equals(""))
						pn = pn + "/";

					pn = pn + fl.getName();
				}

				loadResource(fl, pn);
			}
		}
	}

}
